package com.bwie.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

//全局的过滤器
//模拟一个token验证的逻辑
@Component

public class MyGlobalFilter implements GlobalFilter, Ordered {

    @Override
    //过滤器的主方法：增强请求（响应）的方法
    //参数1：交换机，可以从中获取请求、响应等对象
    //参数2：网关过滤器链：
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取请求或 响应对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();


        //头信息：
//        HttpHeaders headers = request.getHeaders();


        //2.从请求对象中获取token
        //获取了所有的查询参数?name=xx&age=xxx
        MultiValueMap<String, String> queryParams = request.getQueryParams();

        //从查询参数中获取token:?token=xxx&token=yyy
//        List<String> token = queryParams.get("token");
        //从查询参数中获取token:?token=xxx
        String token = queryParams.getFirst("token");

        //3.判断处理
        if(StringUtils.isEmpty(token)|| !token.equals("bobolaoshi")){

            //响应结束，直接从网关就响应回请求
//            response.setComplete();

            //没有权限，友好提示
            //状态码
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //设置响应编码
            response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
            //设置写入响应的的内容
            String result="{\"flag\":false,\"code\":20003,\"message\":\"没有权限\"}";

            //转换为字节
            byte[] resultBytes = result.getBytes(StandardCharsets.UTF_8);

//            DataBuffer wrap = response.bufferFactory().wrap(bytes);
            DataBuffer wrap = response.bufferFactory().wrap(resultBytes);
            //直接设置响应结果,不向下走了
            return response.writeWith(Flux.just(wrap));
        }

        //有权限，放行，转发请求具体微服务
        //继续向下调用下一个过滤器
        return chain.filter(exchange);
    }

    //排序的
    //过滤器的执行顺序
    @Override
    public int getOrder() {
        //数字越小，越先执行的
        return 0;
    }
}
